import { takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'
import { add_product_to_cart, add_product_to_cart_success, delete_product_from_cart, 
  delete_product_from_cart_success, 
  get_product_from_cart, get_product_from_cart_success, modify_cart_mount, modify_cart_mount_success } from '../actions/cart'


function* handleAddProduct(action){
  const { data } = yield axios.post('http://localhost:3005/cart/add', {
    gid: action.payload
  })
  // console.log(data)
  yield put(add_product_to_cart_success(data))
}
// 向服务器发送请求获取购物车列表数据
function* handleGetCarts(){
  const { data } = yield axios.get('http://localhost:3005/cart')
  // console.log(data)
  yield put(get_product_from_cart_success(data))
}

function* handleDeleteCarts(action){
  // console.log(action.payload)
  const {data} = yield axios.delete('http://localhost:3005/cart/delete', {params: {
    cid: action.payload
  }})
  // console.log(action.payload)
  // console.log(data)
  yield put(delete_product_from_cart_success(data.index)) 
}
function* handleCartMount(action){
  // console.log(action)
  const {data} = yield axios.put('http://localhost:3005/cart',
  {cid:action.payload.productId, count: action.payload.count})
  // console.log(data)
  yield put(modify_cart_mount_success(data))
}


export default function* cartSaga() {
  // 将商品添加到购物车中
  yield takeEvery(add_product_to_cart, handleAddProduct)
  // 获取购物车列表数据
  yield takeEvery(get_product_from_cart, handleGetCarts)
  // 删除
  yield takeEvery(delete_product_from_cart, handleDeleteCarts)
  // 修改购物车数量
  yield takeEvery(modify_cart_mount, handleCartMount)
}